<?php
/**
 * Created by PhpStorm.
 * User: zsd
 * Date: 2018/5/3
 * Time: 下午2:32
 */
namespace backend\models;

use yii\base\Exception;
use yii\base\Model;
use yii\web\BadRequestHttpException;
use yii\web\ServerErrorHttpException;
use yii\web\UploadedFile;
use Yii;

class UploadForm extends Model
{
    /**
     * @var UploadedFile
     */
    public $file;

    /**
     * @return array
     */
    public function rules()
    {
        return [
            [
                ['file'],
                'file',
                'skipOnEmpty' => false,
                'extensions'  => ['png', 'jpg', 'jpeg', 'pdf'],
                'maxSize'     => 50 * 1024 * 1024,
                'message'     => '上传失败',
            ],
        ];
    }

    /**
     * @return array
     * @throws Exception
     */
    public function upload()
    {
        if ($this->validate()) {
            list($root_path, $dir, $save_path) = $this->savePath();

            if (is_dir($root_path . $dir)) {
                if (!is_writable($root_path . $dir) && !chmod($root_path . $dir, 0777)) {
                    throw new ServerErrorHttpException('目录没有权限');
                }
            } else {
                mkdir($root_path . $dir . '/', 0777, true);
            }

            $this->file->saveAs($root_path . $dir . $save_path);

            return [
                'path' => $dir . $save_path,
            ];
        } else {
            throw new BadRequestHttpException(current($this->getFirstErrors()));
        }
    }

    /**
     * 存储目录 格式: uploads/201801/名称.后缀
     *
     * @return string
     */
    protected function savePath()
    {
        $root_path = sprintf('%s/web', Yii::$app->basePath);
        $dir       = sprintf('/uploads/%s', date('Ym'));
        $save_path = sprintf('/%s.%s', uniqid(), $this->file->extension);

        return [$root_path, $dir, $save_path];
    }
}
